<template>
  <basic-container>
    <el-row>
      <el-col :span="4">
        <el-tabs type="border-card" style="margin: 10px">
          <el-input placeholder="请输入关键字进行过滤" v-model="filterText"> </el-input>
          <el-tree class="filter-tree treeList" :data="data" :props="defaultProps" :filter-node-method="filterNode" ref="tree" @node-click="nodeClick"></el-tree>
        </el-tabs>
      </el-col>
      <el-col :span="20">
        <el-tabs type="border-card" style="margin: 10px" v-if="isShowDetailTable">
          <el-tab-pane label="扩展页面明细">
            <avue-crud
              v-model="detailForm"
              :option="detailOption"
              :table-loading="detailLoading"
              :data="detailData"
              :permission="permissionList"
              :before-open="beforeOpen"
              ref="detailCrud"
              @row-update="detailUpdate"
              @row-save="detailSave"
              @row-del="detailDel"
              @selection-change="selectionDetailChange"
              @refresh-change="detailRefreshChange"
            >
              <!-- <template slot="menuLeft">
                <el-button type="danger" size="small" icon="el-icon-delete" v-if="this.detailOption.addBtn" @click="detailHandleDelete">删 除 </el-button>
                <span v-if="this.detailConfigId" style="margin-left: 10px">名称：{{ this.packingName }}</span>
              </template> -->
              <!-- <template slot-scope="{ row }" slot="isOutPack">
            <el-tag>{{ row.isOutPack === false ? '否' : '是' }}</el-tag>
          </template> -->
              <template slot="pageAreaListForm">
                <el-select v-model="detailForm.pageAreaList" placeholder="请选择" multiple>
                  <el-option v-for="item in areaList" :key="item.pageAreaCode" :label="item.pageAreaName" :value="JSON.stringify(item)">
                    <span style="float: left">{{ item.pageAreaName }}</span>
                    <!-- <span
                      ><el-input-number
                        style="float: right; margin-right: 50px"
                        v-model="item.sequence"
                        controls-position="right"
                        :min="0"
                        @focus.stop.native=""
                        @blur.stop.native=""
                        @click.stop.native=""
                      ></el-input-number
                    ></span> -->
                  </el-option>
                </el-select>
              </template>
            </avue-crud>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>
<script>
import { getPageTree, getDetail, add, getDetailAttribute, remove } from '@/api/system/extendPage';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getInventoryList } from '@/api/admin/storage';

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      loading: true,
      filterText: '',
      defaultProps: {
        children: 'newChildren',
        label: 'name'
      },
      detailForm: {
        pageAreaList: []
      },
      data: [],
      tableOption: {}, //公用模态框配置信息
      detailLoading: false,
      dialogTitle: '新增',
      showDialog: false,
      detailData: [],
      selectionDetailList: [],
      detailOption: {
        //包装详情列表内容配置
        height: 'calc(100vh - 287px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        menuWidth: 150,
        labelWidth: 150,
        column: [
          {
            label: '字段名称',
            prop: 'lableCnName',
            type: 'search',
            appendClick: () => {
              this.openExpendPropertyLibraryModal();
            },
            rules: [
              {
                required: true,
                message: '请选择字段名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '字段编码',
            prop: 'attributeKey',
            disabled: false,
            rules: [
              {
                required: true,
                message: '请选择字段编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '字段类型',
            prop: 'controlType',
            type: 'select',
            dicData: [
              {
                label: '单行文本',
                value: 'input'
              },
              {
                label: '数字',
                value: 'number'
              },
              {
                label: '时间',
                value: 'datetime'
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择字段类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '字段属性',
            prop: 'isAllowEdit',
            type: 'checkbox',
            dicData: [
              {
                label: '只读',
                value: true
              }
            ]
          },
          {
            label: '引导文字',
            prop: 'defaultTipMessage',
            hide: true
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '呈现形式',
            prop: 'valueSourceType',
            type: 'select',
            dicData: [
              {
                label: '输入',
                value: 'INPUT'
              },
              {
                label: '数据来源',
                value: 'DATASOURCE'
              }
            ],
            hide: true,
            labelTip: '输入：该自定义字段内容为手动输入。数据获取：该自定义字段内容依据页面中某字段信息获取呈现。',
            rules: [
              {
                required: true,
                message: '请选择呈现形式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '宽度',
            prop: 'width'
          },
          {
            label: '数据来源',
            prop: 'valueSource',
            labelTip: '请填写页面中通过某字段信息呈现该自定义字段内容的字段名称。',
            hide: true,
            rules: [
              {
                required: true,
                message: '请输入数据来源',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {
              if (form.valueSourceType == 'DATASOURCE') {
                return {
                  valueSource: {
                    display: true
                  }
                };
              } else {
                return {
                  valueSource: {
                    display: false
                  }
                };
              }
            }
          },
          {
            label: '展示功能区',
            prop: 'pageAreaList',
            type: 'select',
            span: 24,
            hide: true,
            labelTip: '选择在何处添加该扩展属性并决定属性放于扩展区域的第几位。',
            rules: [
              {
                required: true,
                message: '请选择展示功能区',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '状态',
            prop: 'enabled',
            type: 'switch',
            span: 24,
            dicData: [
              {
                label: '禁用',
                value: false
              },
              {
                label: '启用',
                value: true
              }
            ],
            value: true
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            minRows: 3,
            maxRows: 5
            // html: true,
            // formatter: (val) => {
            //   return '<el-popover placement="top-start" title="标题" width="200" trigger="hover" content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。"><el-button slot="reference">hover 激活</el-button></el-popover>';
            // }
          },
          {
            label: '创建人',
            prop: 'createUserName',
            display: false
          },
          {
            label: '创建时间',
            prop: 'createTime',
            display: false
          }
        ]
      },
      areaList: [],
      selectPage: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.customAttributeConfig_add, false),
        // delBtn: this.vaildData(this.permission.customAttributeConfig_delete, false),
        // editBtn: this.vaildData(this.permission.customAttributeConfig_edit, false)
      };
    },
    detailIds() {
      console.log(this.selectionDetailList);
      let ids = [];
      this.selectionDetailList.forEach((ele) => {
        ids.push(ele.id);
      });
      console.log(ids);
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      this.isShowDetailTable = true;
    });
    this.initTree();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    initTree() {
      getPageTree().then((res) => {
        this.data = this._get(res, 'data.data', []);
        for (let i = 0; i < this.data.length; i++) {
          if (this.data[i].children && this.data[i].children.length > 0) {
            this.data[i]['newChildren'] = this.data[i].children;
          }
        }
        console.log(this.data);
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    searchReset() {
      this.query = {};
      this.onLoad();
    },
    searchChange(params, done) {
      this.query = params;
      this.onLoad();
      done();
    },
    refreshChange() {
      this.onLoad();
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetailAttribute({ pageCode: this.selectPage.code, attributeKey: this.detailForm.attributeKey }).then((res) => {
          this.detailForm = this._get(res, 'data.data', {});
          this.detailForm.isAllowEdit = this.detailForm.isAllowEdit ? [true] : [];
          this.detailForm.pageAreaList = this._map(this.detailForm.pageAreaList, (item) => {
            let obj = this._find(this.areaList, { pageAreaId: item.pageAreaId });
            let option = {
              sequence: item.sequence,
              pageAreaName: obj.pageAreaName,
              pageAreaId: item.pageAreaId,
              pageAreaCode: item.pageAreaCode
            };
            return JSON.stringify(option);
          });
        });
      }
      done();
    },
    /**
     * 单击事件
     */
    nodeClick(row) {
      this.selectPage = row;
      this.areaList = this._map(row.children, (item) => {
        return {
          sequence: 0,
          pageAreaName: item.name,
          pageAreaId: item.id,
          pageAreaCode: item.code
        };
      });
      if (row.id != 0) {
        this.onDetailLoad();
      }
    },
    detailSave(row, done, loading) {
      console.log(row);
      row.isAllowEdit = row.isAllowEdit[0];
      row.pageAreaList = this._map(row.pageAreaList, (item) => {
        let obj = JSON.parse(item);
        delete obj.pageAreaName;
        return obj;
      });
      row['pageCode'] = this.selectPage.code;
      add(row).then(
        (res) => {
          this.onDetailLoad();
          this.$message.success(res.data.msg);
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    detailUpdate(row, index, done, loading) {
      row.isAllowEdit = row.isAllowEdit[0];
      row.pageAreaList = this._map(row.pageAreaList, (item) => {
        let obj = JSON.parse(item);
        delete obj.pageAreaName;
        return obj;
      });
      add(row).then(
        () => {
          this.onDetailLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    detailDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove({ pageCode: this.selectPage.code, attributeKey: row.attributeKey });
        })
        .then(() => {
          this.onDetailLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    detailHandleDelete() {
      if (this.selectionDetailList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.detailIds);
        })
        .then(() => {
          this.onDetailLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    /**
     * 查询包装配置详情
     */
    onDetailLoad() {
      this.detailLoading = true;
      getDetail(this.selectPage.code).then((res) => {
        const data = res.data.data;
        this._forEach(data, (item) => {
          item.isAllowEdit = [item.isAllowEdit];
        });
        this.detailData = data;
        this.detailOption.addBtn = true;
        this.detailLoading = false;
        this.selectionDetailClear();
      });
    },
    detailRefreshChange() {
      this.onDetailLoad();
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionDetailClear() {
      this.selectionDetailList = [];
      this.$refs.detailCrud.toggleSelection();
    },
    openAddDialog() {
      this.openAttributeDialog = true;
    },
    /**
     * 获取选择的模态框行数据
     */
    selectAttribute() {
      if (this.selectionAttributeList.length === 0) {
        this.$message.warning('请至少选择一条数据！');
        return;
      }
      this.stagingDetailDialog = true;
      this._forEach(this.selectionAttributeList, (item) => {
        item['attributeId'] = item.id;
        delete item.id;
        item.pagePath = this.selectPage.dictKey;
        item.pageName = this.selectPage.dictValue;
      });
      this.stagingDetailData = this._cloneDeep(this.selectionAttributeList);
    },
    stagingDetailUpdate(row, index, done, loading) {
      this.$set(this.stagingDetailData, [index], row);
      done();
    },
    stagingDetailDel(row, index) {
      this.stagingDetailData.splice(index, 1);
    },
    submitstagingDetail() {
      if (this.stagingDetailData.length === 0) {
        this.$message.warning('数据不能为空！');
        return;
      }
      let attributeKeyList = [];
      this._forEach(this.detailData, (item) => {
        this._forEach(this.stagingDetailData, (rowDataItem) => {
          if (item.attributeKey === rowDataItem.attributeKey) {
            attributeKeyList.push(rowDataItem.attributeKey);
          }
        });
      });
      if (attributeKeyList.length > 0) {
        this.$message.error(`列表中已存在如下编码${attributeKeyList.join('，')}的属性`);
        return;
      }
      add(this.stagingDetailData).then(
        () => {
          this.stagingDetailDialog = false;
          this.openAttributeDialog = false;
          this.onDetailLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        },
        (error) => {}
      );
    },
    onAttributeLoad(page, params = {}) {
      this.attributeLoading = true;
      getAttributeConfig(page.currentPage, page.pageSize, Object.assign(params, this.attributeQuery)).then((res) => {
        const data = res.data.data;
        this.attributePage.total = data.total;
        this.attributeData = data.records;
        this.attributeLoading = false;
      });
    },
    attributeRefreshChange() {
      this.onAttributeLoad(this.attributePage);
    },
    attributeRowClick(row) {
      if (this.attributeOption.selection) {
        this.$refs.attributeCrud.toggleRowSelection(row);
      }
    },
    attributeSearchChange(params, done) {
      this.attributeQuery = params;
      this.onAttributeLoad(this.attributePage);
      done();
    },
    attributeSearchReset() {
      this.attributeQuery = {};
      this.onAttributeLoad(this.attributePage);
    },
    selectionAttributeChange(list) {
      this.selectionAttributeList = list;
    },
    openExpendPropertyLibraryModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择扩展属性库（双击进行选择）',
        url: '/api/mes-admin/customerattribute/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '字段名称',
            prop: 'lableCnName',
            search: true
          },
          {
            label: '字段编码',
            prop: 'attributeKey',
            search: true
          },
          {
            label: '字段类型',
            prop: 'controlType',
            type: 'select',
            search: true,
            dicData: [
              { label: '文本', value: 'input' },
              { label: '文本域', value: 'text' },
              { label: '数字', value: 'number' },
              { label: '日期', value: 'date' },
              { label: '时间', value: 'time' },
              { label: '日期时间', value: 'datetime' },
              { label: '下拉单选(固定值)', value: 'singleSelect' },
              { label: '下拉多选(固定值)', value: 'multiSelect' }
            ]
          },
          {
            label: '字段属性',
            prop: 'isAllowEdit'
          },
          {
            label: '引导文字',
            prop: 'defaultTipMessage'
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '状态',
            prop: 'enabled',
            type: 'switch',
            value: true,
            dicData: [
              { label: '禁用', value: false },
              { label: '启用', value: true }
            ],
            html: true,
            formatter: (val) => {
              switch (val.enabled) {
                case true:
                  return `<span class="stateWords-success">启用</span>`;
                case false:
                  return `<span class="stateWords-danger">禁用</span>`;
                default:
                  break;
              }
            }
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea'
          },
          {
            label: '创建人',
            prop: 'createUserName'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      this.detailForm.lableCnName = this._get(rowData, 'lableCnName', '');
      this.detailForm.attributeKey = this._get(rowData, 'attributeKey', '');
      this.detailForm.controlType = this._get(rowData, 'controlType', '');
      let isAllowEdit = this._get(rowData, 'isAllowEdit', '');
      this.detailForm.isAllowEdit = isAllowEdit ? [true] : '';
      this.detailForm.defaultTipMessage = this._get(rowData, 'defaultTipMessage', '');
      this.detailForm.defaultValue = this._get(rowData, 'defaultValue', '');
      this.detailForm.enabled = this._get(rowData, 'enabled', '');
      this.detailForm.remark = this._get(rowData, 'remark', '');
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}

.custom-informationLabel {
  .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
  .el-form-item__content {
    line-height: 32px;
  }
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}
.treeList {
  height: calc(100vh - 216px);
}
</style>
